package com.yupi.tangoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.tangoj.common.BaseResponse;
import com.yupi.tangoj.common.ErrorCode;
import com.yupi.tangoj.common.ResultUtils;
import com.yupi.tangoj.exception.BusinessException;
import com.yupi.tangoj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.yupi.tangoj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.yupi.tangoj.model.entity.Question;
import com.yupi.tangoj.model.entity.QuestionSubmit;
import com.yupi.tangoj.model.vo.QuestionSubmitVO;
import com.yupi.tangoj.service.QuestionService;
import com.yupi.tangoj.service.QuestionSubmitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/question_submit")
@Slf4j
public class QuestionSubmitController {

    @Autowired
    private QuestionSubmitService questionSubmitService;

    @Autowired
    private QuestionService questionService;

    @PostMapping("/addQuestion")
    public BaseResponse<Long> doQuestion(@RequestBody QuestionSubmitAddRequest questionSubmitAddRequest){

        if (questionSubmitAddRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionSubmit questionSubmit = new QuestionSubmit();
        BeanUtils.copyProperties(questionSubmitAddRequest,questionSubmit);

        questionSubmitService.validQuestionSubmit(questionSubmit,true);

        Question question = questionService.getById(questionSubmit.getQuestionId());
        if (question == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"题目不存在");
        }

        questionSubmitService.save(questionSubmit);
        Long res = questionSubmit.getId();
        if (res <= 0){
            return ResultUtils.error(ErrorCode.OPERATION_ERROR,"提交异常");
        }
        //调用判题服务

        return ResultUtils.success(res)  ;
    }
    /**
     * 获取分页 题目提交信息列表
     * @param questionSubmitRequest
     * @param request
     * @return
     */
    @GetMapping("/getPageSubmit")
    public BaseResponse<Page<QuestionSubmitVO>> getPageSubmit(@RequestBody QuestionSubmitQueryRequest questionSubmitRequest, HttpServletRequest request){
        if (questionSubmitRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long current = questionSubmitRequest.getCurrent();
        Long size = questionSubmitRequest.getPageSize();
        Page<QuestionSubmit> questionSubmitVOPage = questionSubmitService.page(new Page<>(current,size),
                questionSubmitService.getQueryWrapper(questionSubmitRequest));
        return ResultUtils.success(questionSubmitService.getQuestionSubmitVOPage(questionSubmitVOPage,request));
    }
}
